package com.jingbit.utils;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * author: jingbit
 * date: 2018/11/1
 */
public class FileUtils {
    private static String filePath;

    public static boolean deleteFile(String filename) {
        if (TextUtils.isEmpty(filename)) {
            return false;
        }
        File file = new File(filename);
        return file.exists() ? file.delete() : false;
    }

    /**
     * 获取缓存文件地址
     * Environment.DIRECTORY_MUSIC
     * Environment.DIRECTORY_PICTURE
     */
    public static File getTempFile(Context context, String type, String ext) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        //进行图片名称进行拼接
        String fileName = "temp_" + timeStamp;

        //获得该应用包下文件的Pictures目录（如果没有会自动创建）
        File storageDir = context.getExternalFilesDir(type);
        return new File(storageDir, fileName + ext);
    }

    public static File getTempFile(Context context,String fileName, String type, String ext) {
        if (TextUtils.isEmpty(fileName)){
            return getTempFile(context,type,ext);
        }
        //获得该应用包下文件的Pictures目录（如果没有会自动创建）
        File storageDir = context.getExternalFilesDir(type);
        //创建image文件
        return new File(storageDir, fileName + ext);
    }


    public static String getFilePath() {
        return filePath;
    }

    /**
     * 判断外部存储是否可用
     */
    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    /**
     * byte数组转short数组
     * @param src
     * @return
     */
    public static short[] toShortArray(byte[] src) {

        int count = src.length >> 1;
        short[] dest = new short[count];
        for (int i = 0; i < count; i++) {
            dest[i] = (short) ((src[i * 2] & 0xFF) | ((src[2 * i + 1] & 0xFF) << 8));
        }
        return dest;
    }

    /**
     * short数组转byte数组
     * @param src
     * @return
     */
    public static byte[] toByteArray(short[] src) {

        int count = src.length;
        byte[] dest = new byte[count << 1];
        for (int i = 0; i < count; i++) {
            dest[i * 2] = (byte) ((src[i] >> 8) & 0xFF);
            dest[i * 2 + 1] = (byte) (src[i] & 0xFF);
        }

        return dest;
    }
}
